package com.recipe.service.impl;

import cn.hutool.core.lang.Validator;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.recipe.entity.vo.LoginResponse;
import com.recipe.entity.vo.LoginVo;
import com.recipe.mapper.UserMapper;
import com.recipe.entity.User;
import com.recipe.service.UserService;
import com.recipe.util.MD5;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;


/**
 * (User)表服务实现类
 *
 * @author lzk
 * @since 2024-06-14 11:37:52
 */
@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Override
    public LoginResponse isLogin(LoginVo loginVo) {
        String msg;
        LambdaQueryWrapper<User> userWrapper = new LambdaQueryWrapper<>();
        userWrapper.eq(User::getNickname, loginVo.getNickname());
        User user = baseMapper.selectOne(userWrapper);
        if (user == null) {
            msg = "用户名不存在";
        } else {
            String password = loginVo.getPassword();
            String encryptPassword = MD5.encryptPassword(password);

            if(encryptPassword.equals(user.getPassword())){
                msg="登录成功";
            }else{
                msg="密码错误";
            }
        }
        String username = user.getUsername();
        LoginResponse loginResponse = new LoginResponse(msg,username);

        return loginResponse;
    }
    @Override
    @SneakyThrows
    public String register(User user) {

        String phone = user.getPhone();

        boolean mobile = Validator.isMobile(phone);
        if(mobile==false){
            return "手机号格式错误";
        }else{
            if(baseMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getPhone, phone))!=null){
                return "手机号已注册";
            }else{
                String name = user.getNickname();
                String userName = MD5.encryptMD5(phone, name);
                user.setUsername(userName);


                String password = user.getPassword();

                String encryptPassword = MD5.encryptPassword(password);
                user.setPassword(encryptPassword);
                baseMapper.insert(user);
                return "注册成功";
            }
        }
    }

    @Override
    public User getUserByUserName(String username) {
        return baseMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUsername, username));
    }
}

